function updateUrl() {
  if (!wave.getState()) {
    return;
  }
  
  var embedUrl = wave.getState().get('embedUrl');
  if (embedUrl) {
    finishGadget(false);
    return;
  }
    
  var waveId = wave.getState().get('waveId');
  var waveTitle = wave.getState().get('waveTitle');
  var embedWidth = $('#embedWidth').val();
  var embedHeight = $('#embedHeight').val();
  var embedTheme = $('#embedTheme').val();
  
  waveId = encodeURIComponent(waveId);
  waveTitle = encodeURIComponent(waveTitle);
  
  var url = 'http://embed-bot.appspot.com/?id=' + waveId;
  url += '&t=' + waveTitle + '&w=' + embedWidth + '&h=' + embedHeight;
  url += '&th=' + embedTheme;
  
  $('#embedUrl').val(url);
  
}

function updateState(elementId,elementValue) {
  wave.getState().submitDelta({elementId:elementValue});
}

function finishGadget(stateSwitch) {
  if (!wave.getState()) {
    return;
  }
  
  var url = wave.getState().get('embedUrl');
  
  if (stateSwitch) {
    url = $('#embedUrl').val();
    wave.getState().submitDelta({'embedUrl':url});
  }
  
  $('#closeWrapper').html('Working...');
  var msg = '<h3>This wave is also embedded at:</h3>';
  msg += '<h4><a href="' + url + '" target="_blank">' + url + '</a></h4>';
  $('#wrapper').html(msg);
  $('#wrapper').css({'height':'100px'});
  gadgets.window.adjustHeight();
  return;
}
 
function init() {
  if (wave && wave.isInWaveContainer()) {
    $(document).ready(function(){
      $('#embedWidth').keyup(function(){
        updateState($(this).attr('id'), $(this).val());
      });
      $('#embedHeight').keyup(function(){
        updateState($(this).attr('id'), $(this).val());
      });
      $('#embedTheme').change(function(){
        updateState($(this).attr('id'), $(this).val());
      });
      $('#doneButton').bind('click', function() {
        finishGadget(true);
      });
    });
    wave.setStateCallback(updateUrl);
  }
}
gadgets.util.registerOnLoadHandler(init);